#include "Setting.h"
#include "ui_Setting.h"
#include "ConfigManager.h"
#include "ClientManager.h"

#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileInfoList>
#include <QMessageBox>
#include <QUrl>
#include <QDesktopServices>

#ifdef Q_WS_WIN
#include <iostream>
#include <winsock.h>
#else
#include <QStringList>
#endif

Setting::Setting(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::Setting)
{
    m_ui->setupUi(this);
	hide();
}

Setting::~Setting()
{
    delete m_ui;
}

bool Setting::Initialize()
{
	setWindowIcon(QIcon("../img/icon.png"));

	_fileSelect.Initialize(false);
//	_fileSelect.setParent(this);
	_fileSelect.hide();
	connect(m_ui->pushButton_logfind, SIGNAL(clicked()), this, SLOT(on_pushButton_clicked()));
	connect(&_fileSelect, SIGNAL(sigDirectorySelected(QString)), this, SLOT(OnDownloadDirectorySelected(QString)));

	//widget Initialize;
	for (int i = 1; i <= 10; i++)
		m_ui->comboBox_capacity->addItem(QString::number(i*10));

	_textEdits[0][0] = m_ui->plainTextEdit1_1_1;
	_textEdits[0][1] = m_ui->plainTextEdit1_1_2;
	_textEdits[0][2] = m_ui->plainTextEdit1_1_3;

	_textEdits[1][0] = m_ui->plainTextEdit1_2_1;
	_textEdits[1][1] = m_ui->plainTextEdit1_2_2;
	_textEdits[1][2] = m_ui->plainTextEdit1_2_3;

	_textEdits[2][0] = m_ui->plainTextEdit1_3_1;
	_textEdits[2][1] = m_ui->plainTextEdit1_3_2;
	_textEdits[2][2] = m_ui->plainTextEdit1_3_3;

	_textEdits[3][0] = m_ui->plainTextEdit1_4_1;
	_textEdits[3][1] = m_ui->plainTextEdit1_4_2;
	_textEdits[3][2] = m_ui->plainTextEdit1_4_3;

	_groups[0] = m_ui->group_A;
	_groups[1] = m_ui->group_B;
	_groups[2] = m_ui->group_C;
	_groups[3] = m_ui->group_D;
	_groups[4] = m_ui->group_E;
	_groups[5] = m_ui->group_F;

	_checkboxs[0] = m_ui->checkBox_1;
	_checkboxs[1] = m_ui->checkBox_2;
	_checkboxs[2] = m_ui->checkBox_3;
	_checkboxs[3] = m_ui->checkBox_4;

	InitWidget();

	return true;

//	#ifdef Q_WS_WIN
//	#else
//	#endif

}

void Setting::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Setting::InitWidget()
{
	//Combobox
	int idx = m_ui->comboBox_capacity->findText(QString::number(CONFIG_MANAGER->GetLogCapacity()));
	if (idx != -1)
		m_ui->comboBox_capacity->setCurrentIndex(idx);
	else
		m_ui->comboBox_capacity->setCurrentIndex(0);

	//IP
	for (int i = 0; i < 4; i++)
	{
		IPInfo addrInfo = CONFIG_MANAGER->GetNetworkAddr(i); //change variable name
		//CheckBox
		if (addrInfo.isSet)
			_checkboxs[i]->setChecked(true);
		for (int j = 0; j < 3; j++)
			_textEdits[i][j]->setPlainText(addrInfo.addrs[j]);
	}

	//Group:Name
	m_ui->TextEdit_group->setPlainText(CONFIG_MANAGER->GetGroup());
	m_ui->TextEdit_name->setPlainText(CONFIG_MANAGER->GetName());

	//Network Group
	for (int i = 0; i < 6; i++)
	{
		if (_groups[i]->text().at(0) == CONFIG_MANAGER->GetNetworkGroup())
			_groups[i]->setChecked(true);
	}

	//local IP
	m_ui->label_2->setText(CONFIG_MANAGER->GetBroadcastAddress().toString());
	m_ui->label_3->setText(CONFIG_MANAGER->GetLocalAddress().toString());

	//download path
	m_ui->textEdit_downPath->setText(CONFIG_MANAGER->GetDownloadPath());

	//log path
	m_ui->textEdit_logPath->setText(CONFIG_MANAGER->GetLogPath());

	//shortcut enabled
    /// 이제원 주석 m_ui->checkBox_shortcut->setChecked(CONFIG_MANAGER->IsShortcutEnable());
}

//void Setting::SaveToFile(QString fileName, QString backupName, const char *data)
//{
//	bool error = true;
//	if (QFile::copy(fileName, backupName))
//	{
//		FILE *fp = fopen(fileName.toAscii().data(), "wt");
//		if (fp != NULL)
//		{
//			error = (fputs(data, fp) <= 0);
//			fclose(fp);
//		}
//	}
//	if (error)
//	{
//		if (QFile::exists(backupName))
//		{
//			// rollback...
//			QFile::remove(fileName);
//			QFile::rename(backupName, fileName);
//			qDebug() << fileName << "  rollback due to error.";
//		}
//	}
//	else
//		QFile::remove(backupName);
//}

void Setting::on_button_save_clicked()
{
	bool error = false;
	if (QFile::copy("../conf/network.txt", "../conf/network_backup.txt"))
	{
		FILE *fp = fopen("../conf/network.txt", "wt");
		if (fp != NULL)
		{
			for (int i = 0; i < 4 && !error; i++)
			{
				//checkbox state..
				if (_checkboxs[i]->isChecked())
					error = (fputs("1\n", fp) >= 0);
				else
					error = (fputs("0\n", fp) >= 0);
				//IP number
				for (int j = 0; j < 3; j++)
					error = (fputs(QString(_textEdits[i][j]->toPlainText() + '\n').toAscii().data(), fp) < 0);
			}

			if (!error)
			{
				QString group = m_ui->TextEdit_group->toPlainText();
				QString name = m_ui->TextEdit_name->toPlainText();
				if (!CLIENT_MANAGER->IsValidClient(group, name) || CONFIG_MANAGER->IsMyInfo(group, name))
				{
					QString groupName = (group + ':' + name + '\n');
					if (fputs(groupName.toAscii().data(), fp) >= 0)
					{
						char netgroup[2] = {'A', '\0'};
						for (int i = 0; i < 6; i++)
						{
							if (_groups[i]->isChecked())
								netgroup[0] = _groups[i]->text().at(0).toAscii();
						}
						if (fputs(netgroup, fp) < 0)
							error = true;
					}
					else
						error = true;
				}
				else
				{
					QMessageBox::warning(this, "dup client", "already exist client name");
					error = true;
				}
			}
			fclose(fp);
		}
	}
	else
		qDebug() << "network config backup file creation failed";

	if (error)
	{
		if (QFile::remove("../conf/network.txt") &&
			QFile::rename("../conf/network_backup.txt", "../conf/network.txt"))
		{
			qDebug() << "network.txt file was rollbacked due to error..";
		}
	}
	else
		QFile::remove("../conf/network_backup.txt");


	CONFIG_MANAGER->SaveToFile("../conf/log.txt", "../conf/log_backup.txt",
			   m_ui->comboBox_capacity->currentText().toAscii().data());
	CONFIG_MANAGER->SaveToFile("../conf/downdir.txt", "../conf/downdir_backup.txt",
			   m_ui->textEdit_downPath->toPlainText().toAscii().data());
	CONFIG_MANAGER->SaveToFile("../conf/logdir.txt", "../conf/logdir_backup.txt",
			   m_ui->textEdit_logPath->toPlainText().toAscii().data());

	//Todo : add shortcut enabled..
    ///char ch = 'a'; /// 이제원 주석 m_ui->checkBox_shortcut->isChecked() ? '1' : '0';
    /// 이제원 주석 CONFIG_MANAGER->SaveToFile("../conf/shortcut.txt", "../conf/shortcut_backup.txt", *ch);

	int prePort = CONFIG_MANAGER->GetNetworkPort();
	QString preName = CONFIG_MANAGER->GetGroupName();

	// Reinitialize..
	if(CONFIG_MANAGER->NetworkConfigInitialize())
		qDebug() << "config changed";
	else
		qDebug() << "config change failed";

	InitWidget();
	emit sigNetworkConfigChanged(prePort, preName);
	hide();
}

void Setting::on_button_cancel_clicked()
{
	InitWidget();
	hide();
}

void Setting::on_pushButton_logdir_clicked()
{
	QDir dir(CONFIG_MANAGER->GetLogPath());
	QString path = dir.absolutePath();
#ifdef Q_WS_WIN
	path = QDir::toNativeSeparators(dir.absolutePath());
#endif
	QDesktopServices::openUrl(QUrl("file:///" + path));
}

void Setting::on_pushButton_deleteLog_clicked()
{
	QDir dir(CONFIG_MANAGER->GetLogPath());
	QFileInfoList fileList = dir.entryInfoList();
	for (int i = 0; i < fileList.count(); i++)
		dir.remove(fileList.at(i).fileName());
	emit sigLogDeleted();
}

void Setting::on_pushButton_clicked()
{
	if (_fileSelect.isHidden())
		_fileSelect.show();
}

void Setting::OnDownloadDirectorySelected(QString dirPath)
{
	qDebug() << "dirPath : " << dirPath;
	int tabIdx = m_ui->tabWidget->currentIndex();
	if (tabIdx == 1) //Log tab
	{
		m_ui->textEdit_logPath->clear();
		m_ui->textEdit_logPath->setText(dirPath + '/');
	}
	else if (tabIdx == 2) //Download tab..
	{
		m_ui->textEdit_downPath->clear();
		m_ui->textEdit_downPath->setText(dirPath + '/');
	}
}

void Setting::on_checkBox_clicked(bool checked)
{
	CONFIG_MANAGER->SetShortcutEnable(checked);
}
